package system_code.DeleteFile;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws IOException {
        System.out.print("请输入要扫描的路径:");
        Scanner scanner = new Scanner(System.in);
        //rootDir为起始目录
        File rootDir = new File(scanner.next());
        if(!rootDir.isDirectory()){
            System.out.println("该目录不存在");
            return;
        }
        System.out.println("请输入您要搜索的关键词:");
        //toDelete是要删除的目标文件
        String toDelete = scanner.next();
        //深度优先遍历查找
        dfs(rootDir, toDelete);
    }

    private static void dfs(File rootDir, String toDelete) throws IOException {
        //通过listFiles可以或许到目录文件的下一级
        File[] files = rootDir.listFiles();
        if(files == null){
            return;
        }
        //到了这里，目录非空
        for(File f : files){
            if(f.isDirectory()){
                //若还是目录，继续找下一级
                dfs(f, toDelete);
            }else{
                //若不是目录，判定文件名是否相同
                checkFile(f, toDelete);
            }
        }
    }
    private static void checkFile(File f, String toDelete) throws IOException {
        //或许文件名，检测是否包含子串toDelete
        if(f.getName().contains(toDelete)){
            System.out.println("您要删除的文件:" +
                    toDelete + "被" + f.getCanonicalPath() + "包含了，是否删除？(Y/N):");
            Scanner scanner = new Scanner(System.in);
            String chose = scanner.next();
            if(chose.equals("Y") || chose.equals("y")){
                f.delete();
            }
        }
    }
}
